<template>
  <!--	这个必须加否则页面整体出现下拉情况-->
  <!--	@touchmove.stop.prevent="() => {}"-->
  <gui-page
    ref="guiPage"
    :customHeader="true"
    :headerClass="['gui-bg-white', 'gui-dark-bg-level-1']"
  >
    <!-- 自定义头部导航 -->
    <template v-slot:gHeader>
      <view
        style="height: 44px"
        class="gui-flex gui-nowrap gui-rows gui-align-items-center gui-bg-white gui-border-b"
      >
        <!-- 使用组件实现返回按钮及返回首页按钮 -->
        <gui-xhs-header-leading
          :home="false"
          @goBack="goBack"
        ></gui-xhs-header-leading>

        <!-- 导航文本此处也可以是其他自定义内容 -->
        <text
          class="gui-h5 gui-blod gui-flex1 gui-ellipsis gui-primary-text xhs-margin-right-20"
        >
          <gui-search
            class="xhs-margin-right-20"
            @clear="searchStr = ''"
            :kwd="searchStr"
            @inputting="inputting"
            @confirm="confirm"
          ></gui-search>
        </text>
        <!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
        <!-- 实际宽度请根据自己情况设置 -->
      </view>
    </template>

    <template v-slot:gBody>
      <view class="gui-flex1 gui-flex gui-column">
        <!-- #ifdef MP -->
        <view style="height: 12.8rpx; background: #f8f8f8"></view>
        <!-- #endif -->

        <!-- #ifdef H5 -->
        <view style="height: 92.8rpx; background: #f8f8f8"></view>
        <!-- #endif -->

        <!-- #ifdef APP-PLUS -->
        <view style="height: 12.8rpx; background: #f8f8f8"></view>
        <!-- #endif -->

        <view
          v-show="headerShow"
          id="header"
          class="search-fixed-top gui-bg-white"
          style="padding: 10rpx 30rpx"
        >
          <gui-switch-navigation
            :activeLineClass="['gui-xhs-red']"
            :isCenter="true"
            activeDirection="center"
            textAlign="center"
            :items="tabs"
            :size="150"
            :currentIndex="currentIndex"
            @change="navchange"
          ></gui-switch-navigation>
        </view>

        <swiper
          :current="currentIndex"
          @change="swiperChange"
          :style="{ height: swiperHeight + 'px', width: '750rpx' }"
        >
          <!-- 轮播项目数量对应 上面的选项标签 -->
          <swiper-item class="gui-bg-gray">
            <view id="content-wrap1" style="padding: 0 26rpx">
              <view class="gui-flex gui-row gui-space-between">
                <view
                  class="gui-waterfall-item"
                  v-for="(lists, index1) in noteList1"
                  :key="index1"
                >
                  <view
                    :id="'waterfall1' + index1 + index2"
                    @tap="goDetail(notes)"
                    class="gui-bg-white gui-border-radius"
                    style="
                      overflow: hidden;
                      margin-bottom: 16rpx;
                      position: relative;
                    "
                    v-for="(notes, index2) in lists"
                    :key="index2"
                  >
                    <gui-image
                      @imgLoad="imgLoad"
                      :src="notes.firstPicture"
                      :width="340"
                      style="border-radius: 16rpx"
                    ></gui-image>
                    <view v-show="notes.noteTitle" class="masking">
                      <text class="masking-text">{{ notes.noteTitle }}</text>
                    </view>
                    <view v-if="notes.noteType == 2" class="zhibo-icon">
                      <image
                        src="/static/noteList/zhibo icon@2x.png"
                        style="width: 36rpx; height: 36rpx"
                      ></image>
                    </view>
                    <!--<view-->
                    <!--  class="gui-flex gui-row gui-space-between xhs-margin-top-15"-->
                    <!--&gt;-->
                    <!--  <view style="width: 28px; height: 28px">-->
                    <!--    <image-->
                    <!--      style="width: 28px; height: 28px; margin-left: 16rpx"-->
                    <!--      class="gui-list-image ucenter-face-image"-->
                    <!--      :src="notes.authorAvatar"-->
                    <!--      mode="aspectFill"-->
                    <!--    ></image>-->
                    <!--  </view>-->
                    <!--  &lt;!&ndash;负值越小越往左&ndash;&gt;-->
                    <!--  <view-->
                    <!--    style="-->
                    <!--      font-size: 22rpx;-->
                    <!--      color: #5a5a5a;-->
                    <!--      margin-left: 20rpx;-->
                    <!--      line-height: 29rpx;-->
                    <!--      width: 200rpx;-->
                    <!--    "-->
                    <!--  >-->
                    <!--    <text>{{ notes.authorName }}</text>-->
                    <!--    <br />-->
                    <!--    <text style="color: #acacac">{{-->
                    <!--      formatDate(notes.createTime)-->
                    <!--    }}</text>-->
                    <!--  </view>-->
                    <!--  <view-->
                    <!--    style="-->
                    <!--      margin-right: 16rpx;-->
                    <!--      color: #acacac;-->
                    <!--      line-height: 32rpx;-->
                    <!--      font-size: 24rpx;-->
                    <!--      text-align: center;-->
                    <!--    "-->
                    <!--    @tap.stop="upNote(notes)"-->
                    <!--  >-->
                    <!--    <text-->
                    <!--      :class="[-->
                    <!--        'gui-icons',-->
                    <!--        'gui-block',-->
                    <!--        'ranking-lists-zan-icon',-->
                    <!--        notes.isUp ? 'zan-active' : '',-->
                    <!--      ]"-->
                    <!--    >-->
                    <!--      {{ notes.isUp ? "&#xe605;" : "&#xe6ad;" }}-->
                    <!--      <text style="color: #5a5a5a; margin-left: 5rpx">{{-->
                    <!--        notes.upCount-->
                    <!--      }}</text>-->
                    <!--    </text>-->
                    <!--  </view>-->
                    <!--</view>-->
                  </view>
                </view>
              </view>
            </view>

            <!-- 加载组件 -->
            <gui-loadmore
              v-show="currentIndex == 0"
              ref="loadmorecom1"
              :status="1"
              style="padding-bottom: 30rpx"
            ></gui-loadmore>
          </swiper-item>
          <swiper-item class="gui-bg-gray">
            <!--数值越大中间边距越小-->
            <view
              id="content-wrap2"
              style="
                padding: 0 15rpx;
                display: flex;
                flex-direction: column;
                gap: 32rpx;
              "
            >
              <view
                v-for="(item, index) in noteList2"
                :key="index"
                class="gui-list-items"
                @click="goNoteDetail(item)"
                style="padding-left: 30rpx"
              >
                <view
                  class="gui-list-image gui-relative"
                  style="width: 100rpx; height: 100rpx"
                >
                  <image
                    @tap="goCard(item.authorId)"
                    class="gui-list-image"
                    style="width: 100rpx; height: 100rpx; border-radius: 100rpx"
                    mode="aspectFill"
                    :src="item.userPic"
                  ></image>
                </view>
                <view
                  class="gui-list-body"
                  style="padding: 0; display: flex; align-items: center"
                >
                  <view
                    class="gui-list-title"
                    style="flex: 1; flex-direction: column; text-align: left"
                  >
                    <view
                      class="gui-list-title-text gui-primary-text"
                      style="width: 100%"
                      >{{ item.nickname }}</view
                    >
                    <view
                      class="gui-list-body-desc gui-color-gray"
                      style="width: 100%"
                      >{{ item.description }}
                    </view>
                  </view>
                  <text
                    v-show="item.userId"
                    class="gui-list-title-desc gui-bold gui-text-center"
                  >
                    <view
                      v-show="item.isFollow"
                      @tap.stop="cancelfollowAuthor(item)"
                      class="gui-button-mini xhs-border-radius50 xhs-border-gray"
                      style="
                        width: 150rpx;
                        margin-right: 20rpx;
                        text-align: center;
                      "
                    >
                      <text class="gui-icons xhs-font24">取消关注</text>
                    </view>
                    <view
                      v-show="!item.isFollow"
                      @tap.stop="followAuthor(item)"
                      type="default"
                      class="gui-button-mini xhs-border-radius50 xhs-border-pink"
                      style="width: 150rpx; margin-right: 20rpx"
                    >
                      <text style="color: #e22e4d" class="gui-icons xhs-font24"
                        >关注
                      </text>
                    </view>
                  </text>
                </view>
              </view>
            </view>
            <gui-loadmore
              v-show="currentIndex == 1"
              ref="loadmorecom2"
              :status="1"
              style="padding-bottom: 30rpx"
            ></gui-loadmore>
          </swiper-item>
        </swiper>
      </view>
    </template>
  </gui-page>
</template>
<script>
import graceJS from "@/Grace6/js/grace.js";
import getWebSocketClient from "@/Grace6/js/ws";
// 模拟数据
import dataObj from "@/Grace6/demoData/data.js";
import commonMixin from "@/mixin/commonMinxin";
export default {
  mixins: [commonMixin],
  data() {
    return {
      // 全屏 loading
      // 顶部选项卡标签
      tabs: [
        { id: 1, name: "笔记" },
        { id: 2, name: "用户" },
        // {id:3,name:'商品'},
      ],
      // 顶部选项卡标签 选中选项的 索引
      currentIndex: 0,
      headerHeight: 0,
      swiperHeight: 0,
      defaultSwiperHeight: 0,
      noteList1: [[], []],
      noteList2: [[], []],
      noteList3: [[], []],
      // 用于记录是否有 api 请求正在执行
      apiLoadingStatus1: false,
      apiLoadingStatus2: false,
      apiLoadingStatus3: false,
      page1: 1,
      page2: 1,
      page3: 1,
      loadMoreTimer1: null,
      loadMoreTimer2: null,
      loadMoreTimer3: null,
      searchStr: "",
      scrollTop: 0,
      headerShow: true,
      navType: null,
      accessToken: "",
      userId: "",
    };
  },
  onPageScroll: function (e) {
    // Always keep header visible
    this.headerShow = true;
    // Store current scroll position for reference
    this.scrollTop = e.scrollTop;
  },
  watch: {
    currentIndex(newVal, OldVal) {
      this.$nextTick(() => {
        //切换时刷新高度
        this.setSwiperHeight(this.currentIndex + 1);
      });
    },
  },
  methods: {
    goNoteDetail(item) {
      console.log(item.userId);
      if (item.userId != uni.getStorageSync("userId")) {
        uni.navigateTo({
          url: `/pages/card/card?authorId=${item.userId}&accessToken=${this.accessToken}&userId=${this.userId}`,
        });
      } else {
        switch (uni.getSystemInfoSync().platform) {
          case "android":
            let ddd = {
              hideNavBar: "1",
              hideTotalNavBar: "1",
              hideBottomSafeBar: "1",
              url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/my?accessToken=${this.accessToken}&userId=${this.userId}`,
            };
            let d = JSON.stringify(ddd);
            console.log(d, "都是对的");
            window.AndroidBridge.myHomepage(d);
            console.log("运行Android上");
            break;
          case "ios":
            window.webkit.messageHandlers.myHomepage.postMessage({
              hideNavBar: "1",
              hideTotalNavBar: "1",
              hideBottomSafeBar: "1",
              url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/my?accessToken=${this.accessToken}&userId=${this.userId}`,
            });
            break;
          default:
            console.log("运行在开发者工具上");
            break;
        }
      }
    },
    goCard(authorId) {
      return uni.app.goCard(authorId);
    },
    goBack() {
      uni.navigateBack();
      // if (this.navType) {
      //   uni.navigateBack();
      // } else {
      //   switch (uni.getSystemInfoSync().platform) {
      //     case "android":
      //       window.AndroidBridge.backEvent();
      //       console.log("运行Android上");
      //       break;
      //     case "ios":
      //       window.webkit.messageHandlers.backEvent.postMessage({});
      //       break;
      //     default:
      //       console.log("运行在开发者工具上");
      //       break;
      //   }
      // }
    },
    confirm(e) {
      console.log(e);
      this.page1 = 1;
      this.page2 = 1;
      this.noteList1 = [[], []];
      this.noteList2 = [];
      this.addHistory();
      this.getNotes1();
      this.getNotes2();
    },
    // 监听输入
    inputting: function (e) {
      console.log(e);
      this.searchStr = e;
    },
    //格式化时间
    formatDate(date) {
      return uni.app.formatDate(date);
    },
    //点赞笔记
    upNote(notes) {
      uni.app.post("/blog/action/upReply", notes, "json", "", (res) => {
        console.log(res.data);
        if (res.data) {
          notes.isUp = true;
          notes.upCount++;
        } else {
          notes.isUp = false;
          notes.upCount--;
        }
      });
    },
    //图片加载成功后重新 计算高度防止高度不够无法滑动
    imgLoad() {
      this.$nextTick(() => {
        this.setSwiperHeight(this.currentIndex + 1);
      });
    },
    //计算高度
    setSwiperHeight(i) {
      var swiperHeightTimer = null;
      if (swiperHeightTimer != null) {
        clearTimeout(swiperHeightTimer);
      }
      swiperHeightTimer = setTimeout(() => {
        // console.log('设置了高度')
        let element = "#content-wrap" + i.toString();
        // console.log(element)
        let query = uni.createSelectorQuery().in(this);
        query.select(element).boundingClientRect();
        query.exec((res) => {
          // console.log(res)
          if (res && res[0]) {
            // console.log('当前Swiper'+ i +'高度' + res[0].height)
            let contentHeight = res[0].height;
            // Add extra padding for the loadmore component
            const extraHeight = uni.upx2px(80); // Extra height for loadmore

            if (
              contentHeight == 0 ||
              contentHeight < this.defaultSwiperHeight
            ) {
              // console.log('当前高度小于默认高度' + this.defaultSwiperHeight)
              this.swiperHeight = this.defaultSwiperHeight;
            } else {
              this.swiperHeight = contentHeight + extraHeight;
            }
            // console.log('赋值了高度 当前currentIndex+1=' + (this.currentIndex+1) +' getNodes监听的数据' + this.swiperHeight)
          }
        });
      }, 100);
    },
    navchange: function (index) {
      this.currentIndex = index;
    },
    swiperChange: function (e) {
      var index = e.detail.current;
      this.currentIndex = index;
    },
    //进入详情
    goDetail(e) {
      console.log(e.noteId);
      let detail = "";
      if (e.noteType == 1) {
        detail = "detail";
      } else if (e.noteType == 2) {
        detail = "videoDetail";
      }

      let ddd = {
        hideNavBar: "1",
        hideTotalNavBar: "0",
        hideBottomSafeBar: "0",
        url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/notes/${detail}/${detail}?noteId=${e.noteId}&accessToken=${
          this.accessToken
        }&userId=${this.userId}`,
      };

      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let d = JSON.stringify(ddd);
          window.AndroidBridge.pushNewWebVC(d);
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.pushNewWebVC.postMessage(ddd);
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },
    getNotes1(isReload) {
      this.apiLoadingStatus1 = true;
      const that = this;
      let params = {
        authorId: uni.getStorageSync("userId"),
        ipRealAddress: "",
        keyword: this.searchStr,
        limit: 10,
        myStarById: "",
        myUpById: "",
        noteCategory: 0,
        noteId: "",
        noteTitle: "",
        offset: this.page1,
      };
      uni.app.post("/blog/note/getNotes", params, "", "", (res) => {
        if (res.code == 2000) {
          console.log("getNotes1当前页" + that.page1);
          console.log("总页数" + res.data.pages);
          if (that.page1 <= res.data.pages) {
            let notes = res.data.records;
            //填充数组[此处的 notes 数据应该来自与api接口数据]
            //数据格式见 "/data/data.js"
            for (var i = 0; i < notes.length; i++) {
              if (i % 2 == 0) {
                that.noteList1[0].push(notes[i]);
              } else {
                that.noteList1[1].push(notes[i]);
              }
            }
            this.$nextTick(() => {
              this.setSwiperHeight(1);
            });
            if (that.page1 == res.data.pages) {
              this.$refs.loadmorecom1.nomore();
            } else {
              that.page1 = that.page1 + 1;
              this.$refs.loadmorecom1.stoploadmore();
            }
            that.apiLoadingStatus1 = false;
          } else if (res.data.pages == 0) {
            that.apiLoadingStatus1 = false;
            this.$refs.loadmorecom1.nomore();
          }
          if (isReload) {
            uni.stopPullDownRefresh();
          }
        }
      });
    },
    getNotes2(isReload) {
      this.apiLoadingStatus2 = true;
      const that = this;
      uni.app.post(
        "/blog/author/getAuthorList",
        {
          limit: 10,
          offset: this.page2,
          keyword: this.searchStr,
          authorId: uni.getStorageSync("userId"),
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            console.log("getNotes2当前页" + that.page2);
            console.log("总页数" + res.data.pages);
            if (that.page2 <= res.data.pages) {
              let notes = res.data.records;

              if (this.page2 == 1) {
                this.noteList2 = notes;
              } else {
                this.noteList2 = [...this.noteList2, ...notes];
              }

              this.$nextTick(() => {
                this.setSwiperHeight(2);
              });
              if (that.page2 == res.data.pages) {
                this.$refs.loadmorecom2.nomore();
              } else {
                that.page2++;
                this.$refs.loadmorecom2.stoploadmore();
              }
              that.apiLoadingStatus2 = false;
            } else if (res.data.pages == 0) {
              this.$refs.loadmorecom2.nomore();
              that.apiLoadingStatus2 = false;
            }
            if (isReload) {
              uni.stopPullDownRefresh();
            }
          }
        },
      );
    },
    cancelfollowAuthor(author) {
      console.log(author);
      uni.app.post(
        "/blog/action/cancelFollowAuthor",
        {
          authorId: uni.getStorageSync("userId"),
          followAuthorId: author.userId,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            author.isFollow = false;
          }
        },
      );
    },
    followAuthor(author) {
      console.log(author);
      uni.app.post(
        "/blog/action/followAuthor",
        {
          authorId: uni.getStorageSync("userId"),
          followAuthorId: author.userId,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            author.isFollow = true;
          }
        },
      );
    },
    addHistory() {
      if (uni.app.isEmpty(this.searchStr)) {
        return;
      }
      uni.app.post(
        "/blog/note/addHistory",
        { authorId: uni.getStorageSync("userId"), content: this.searchStr },
        "json",
        "",
        (res) => {},
      );
    },
  },
  //下拉刷新
  onPullDownRefresh: function () {
    if (this["apiLoadingStatus" + (this.currentIndex + 1)]) {
      uni.stopPullDownRefresh();
      return;
    }
    this["page" + (this.currentIndex + 1)] = 1;
    this["noteList" + (this.currentIndex + 1)] = [[], []];
    this["getNotes" + (this.currentIndex + 1)](true);
  },
  onLoad: function (e) {
    console.log(e);
    this.accessToken = e.accessToken;
    this.userId = e.userId;
    this.navType = e.type;
    // 页码加载时第一次加载数据
    this.$nextTick(() => {
      this.searchStr = e.searchStr;
      this.addHistory();

      const query = uni.createSelectorQuery().in(this);
      query
        .select("#header")
        .boundingClientRect((data) => {
          if (data) {
            console.log("header");
            console.log(data);
            this.headerHeight = data.height;
          }
        })
        .exec();
      this.getNotes1();
      this.getNotes2();
    });
  },
  onReachBottom: function () {
    console.log("我到第" + (this.currentIndex + 1) + "最低端了");
    console.log(this["apiLoadingStatus" + (this.currentIndex + 1)]);
    if (this["apiLoadingStatus" + (this.currentIndex + 1)]) {
      return;
    }
    // 获取加载组件状态看一下是否还能继续加载
    // 保证触底只执行一次加载
    console.log("timer");
    console.log(this["loadMoreTimer" + (this.currentIndex + 1)]);
    if (this["loadMoreTimer" + (this.currentIndex + 1)] != null) {
      clearTimeout(this["loadMoreTimer" + (this.currentIndex + 1)]);
    }
    this["loadMoreTimer" + (this.currentIndex + 1)] = setTimeout(() => {
      var status =
        this.$refs["loadmorecom" + (this.currentIndex + 1)].loadMoreStatus;
      if (status != 0) {
        return null;
      }
      this.$refs["loadmorecom" + (this.currentIndex + 1)].loading();
      // 此处开启加载动画执行加载数据的函数
      this["getNotes" + (this.currentIndex + 1)]();
      // this.swiperHeight = this['swiperHeight'+(this.currentIndex+1)]
      // console.log('赋值了高度 当前currentIndex+1='+ (this.currentIndex+1) +' oonReachBottom监听的数据' + this.swiperHeight)
    }, 50);
  },
  mounted: function () {
    var mountedTimer = null;
    if (mountedTimer != null) {
      clearTimeout(mountedTimer);
    }
    mountedTimer = setTimeout(() => {
      // 01. 获取页面主体高度
      graceJS.getRefs("guiPage", this, 0, (ref) => {
        ref.getDomSize("guiPageBody", (e) => {
          this.swiperHeight = e.height - uni.upx2px(110) - 92.8; //导航栏高度
          this.defaultSwiperHeight = e.height - uni.upx2px(110);
        });
      });
    }, 100);
  },
};
</script>
<style scoped>
.search-fixed-top {
  position: fixed;
  z-index: 999;
  left: 0;
  top: 85rpx;
  width: 100%;
}

/*数值越大屏幕中边距越小 左右模块的宽度*/
.gui-waterfall-item {
  width: 340rpx;
}

.gui-waterfall-items {
  margin-bottom: 15rpx;
}

.gui-block {
  margin-top: 10rpx;
}
.masking {
  position: absolute;
  bottom: 0;
  font-family: PingFang SC-Bold;
  padding: 18rpx;
  width: 100%;
  border-radius: 0 0 16rpx 16rpx;
  color: #ffffff;
  font-weight: bold;
  line-height: 36rpx;
  background-color: rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(3rpx);
  -webkit-backdrop-filter: blur(3rpx);

  .masking-text {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 40rpx;
  }
}
.zhibo-icon {
  position: absolute;
  right: 12rpx;
  top: 12rpx;
}
</style>
